<template >
  <div class="search-container">
    <!-- 搜索框 -->
    <!-- 
        Tips: 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮
     -->
    <form class="search-form" action="/">
      <van-search
      background="#3296fa"
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow=false"
      />
    </form>

    <!-- /搜索框 -->
        <!-- 搜索结果 -->
    <SearchResult
     v-if="isResultShow"
     :search-text = 'searchText'
     />
    <!-- /搜索结果 -->

     <!-- 联想建议 -->
    <SearchSuggestion 
    :search-text = 'searchText'
    v-else-if="searchText"
    @search='onSearch'/>
    <!-- /联想建议 -->
        <!-- 搜索历史记录 -->
        <SearchHistory v-else  
        :search-histories="SearchHistories"
        @claer-search-histories='SearchHistories=[]' 
        @search='onSearch'/>
    <!-- 搜索历史记录 -->

   


  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import {getItem, setItem} from '@/utils/storage'
export default {
    data() {
        
        return {
            name:'SearchIndex',
            searchText:'',
            isResultShow:false, //控制搜索结果的显示
            SearchHistories:getItem('TOUTIAO_SEARCH_HISTORIES') || [],
        }
    },
    watch:{
        SearchHistories(val){
            setItem('TOUTIAO_SEARCH_HISTORIES',val)
        }
    },
    components:{SearchHistory,SearchSuggestion,SearchResult},
    methods: {
        onSearch(val){
            // 更新文本框内容
            this.searchText = val

                // 存储搜索历史数据 不能重复 最新的放前面
                const index = this.SearchHistories.indexOf(val)
                if(index !==-1){
                    this.SearchHistories.splice(index,1)
                }
                this.SearchHistories.unshift(val)

            // 渲染搜索结果
            this.isResultShow=true
        },
        onCancel(){
           this.$router.back()
        },

    },
};
</script>

<style scoped lang="less">
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>